package se.webbzon.boltzmann.world;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import se.webbzon.boltzmann.environment.AbstractEnvironment;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldeditor.WorldAreaBlueprint;
import se.webbzon.oschi01.worldeditor.WorldAreaBlueprintException;
import se.webbzon.oschi01.worldeditor.WorldAreaReader;
import se.webbzon.oschi01.worldeditor.WorldAreaReaderException;

public abstract class AbstractWorldLoader {
	
	// The abstract environment associated with this abstract world loader
	private final AbstractEnvironment env;
	
	// The world area name to load
	private final String worldAreaName;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public AbstractWorldLoader(	AbstractEnvironment env,
								String worldAreaName) {
		this.env = env;
		this.worldAreaName = worldAreaName;
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Return the abstract environment associated with this 
	 * abstract world loader. **/
	public AbstractEnvironment getEnvironment() {
		return env;
	}
	
	/** Returns the name of the available world area for loading
	 * from this AbstractWorldLoader. **/
	public String getWorldAreaName() {
		return worldAreaName;
	}
	
	/** Loads the constructor specified world area from this AbstractWorldLoader. **/
	public WorldArea load() throws WorldLoaderException {
		URL worldUrl = getClass().getClassLoader().getResource("world/" + worldAreaName + ".pi3e");
		if (worldUrl == null)
			throw new WorldLoaderException(	"No world area was found with the "+
											"name \"" + worldAreaName + "\".");
		else try {
			WorldAreaReader reader = new WorldAreaReader();
			WorldAreaBlueprint blueprint = reader.load(worldUrl);
			return blueprint.load(	env.getInflatorGroup(), 
									new ArrayList<WorldAreaBlueprintException>());
			
		} catch (WorldAreaReaderException | WorldAreaBlueprintException | IOException e) {
			throw new WorldLoaderException(e);
		}
	}

}
